import sys
from typing import Optional

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QTableWidget, QFrame, QAbstractItemView, QHeaderView, QTableWidgetItem


class DeviceStatusList(QTableWidget):
    __devIconConnected = None
    __devIconDisconnected = None

    def __init__(self, parent=None):
        super(DeviceStatusList, self).__init__(parent)
        self.setAlternatingRowColors(True)
        self.setObjectName('DevsTable')
        self.setColumnCount(3)
        self.setMinimumHeight(150)
        self.setMinimumWidth(250)
        # tableWidget.setMaximumWidth(350)
        self.setShowGrid(False)  # 不显示网格线
        self.setFocusPolicy(Qt.NoFocus)  # 设置表格不接受焦点
        self.setFrameShape(QFrame.NoFrame)  # 去除表格边框
        self.setSelectionMode(QAbstractItemView.NoSelection)  # 设置为不可选择模式
        self.setSelectionMode(QAbstractItemView.SingleSelection)
        self.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.horizontalHeader().setSectionResizeMode(0, QHeaderView.Fixed)
        self.horizontalHeader().setSectionResizeMode(2, QHeaderView.Fixed)
        self.setColumnWidth(0, 80)
        self.setColumnWidth(2, 75)
        self.verticalHeader().setVisible(False)
        self.horizontalHeader().setVisible(False)

    def setStatusIcons(self, iconConnected: QIcon, iconDisconnected: QIcon):
        self.__devIconConnected = iconConnected
        self.__devIconDisconnected = iconDisconnected

    # 先使用setRowCount设置好行数，然后才能执行setRow设置每行具体信息
    # 更新设备列表及设备状态
    # 第二个参数为设备名称, 第三个参数为IP或串口号, 第四个参数为连接状态
    # devs = [['camera - 1', '192.168.1.1', True], ['scanner - 1', 'COM1', False]]
    def setRow(self, rowIndex: int, name: str, info: str, bConnected: Optional[bool] = None):
        count = self.rowCount()
        if rowIndex >= count:
            return
        table_item = QTableWidgetItem(name)
        self.setItem(rowIndex, 0, table_item)
        table_item = QTableWidgetItem(info)
        self.setItem(rowIndex, 1, table_item)
        if bConnected is not None:
            if bConnected is True:
                table_item = QTableWidgetItem('连接')
                if self.__devIconConnected is not None:
                    table_item.setIcon(self.__devIconConnected)
            else:
                table_item = QTableWidgetItem('未连接')
                if self.__devIconDisconnected is not None:
                    table_item.setIcon(self.__devIconDisconnected)
            self.setItem(rowIndex, 2, table_item)

    # 根据IP或者串口号更新设备状态（只更新状态，不修改列表项）
    # info: 例如 '192.168.1.1' or 'COM1'
    def updateStatus(self, info: str, bConnected: bool):
        try:
            tableRowCount = self.rowCount()
            # 遍历所有行
            for row in range(tableRowCount):
                devInfo = self.item(row, 1).text()
                if devInfo == info:
                    table_item = self.item(row, 2)
                    if table_item.text() == '连接' and bConnected is True:
                        continue
                    if table_item.text() == '未连接' and bConnected is False:
                        continue
                    print(f'修改{info}的状态为:{bConnected}')
                    if bConnected is True:
                        table_item.setText('连接')
                        if self.__devIconConnected is not None:
                            table_item.setIcon(self.__devIconConnected)
                    else:
                        table_item.setText('未连接')
                        if self.__devIconDisconnected is not None:
                            table_item.setIcon(self.__devIconDisconnected)
                    break
        except Exception as e:
            print(sys.exc_info())


    def resizeColumnWidth(self):
        #size = editor.fontMetrics().boundingRect(text).size()
        tableRowCount = self.rowCount()
        # 遍历所有行
        maxCharNum = 0
        for row in range(tableRowCount):
            name = self.item(row, 0).text()
            if len(name) > maxCharNum:
                maxCharNum = len(name)
        if maxCharNum > 0:
            width = maxCharNum*14 # 暂时认为一个字占14个像素
            if width > self.width()/2:
                width = self.width()/2
            self.setColumnWidth(0, width)
            #self.update()
